<?php
/**
后台类目调整，家具日用里的「床上用品」16原来是二级分类，目前需要降到三级（所属二级分类 435布艺家纺）。原来床上用品下的三级分类，也对应降到四级
需求：
    处理商品数据，原 二级分类 = 16 床上用品 的商品 改为  二级分类=435布艺家纺 三级分类=16 床上用品，
    商品原有的三级分类，改为 四级分类
 */

use \Biz\model\GoodsBasicInfo;
use \Doraemon\model\Category;
//
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

//查询二级分类为16的商品
$second_category_id = 16;
$targetId = 435;//布艺家纺

$where = [
    'second_category_id' => $second_category_id
];
$list = \Biz\model\GoodsBasicInfo::select_master('*', $where);


$goodsIds = array_column($list, 'goods_id');//需要修改的商品id
var_dump($goodsIds);

Category::action(function() use ($second_category_id, $targetId) {
    //修改二级分类的父id,修改类目深度
    $rs = Category::updateCataInfoById($second_category_id, ['deep[+]' => 1, 'father_id' => $targetId]);
    var_dump(['修改二级分类的父id', $rs]);

    //获取子分类,修改子分类的类目深度
    $children = Category::getChildrenById($second_category_id);
    foreach ($children as $v) {
        $rs = Category::updateCataInfoById($v['id'], ['deep[+]' => 1]);
        var_dump(['修改子分类的类目深度,id' . $v['id'], $rs]);
    }
});

GoodsBasicInfo::action(function() use ($list, $targetId, $second_category_id) {
    //商品分类修改
    foreach ($list as $value) {
        $rs = GoodsBasicInfo::update([
            'second_category_id'    => $targetId,
            'third_category_id'     => $second_category_id,
            'four_category_id'     => $value['third_category_id'],
            'edittime' => date("Y-m-d H:i:s"),
        ], ['goods_id' => $value['goods_id']])->rowCount();
        var_dump(['修改商品分类,id' . $value['goods_id'], $rs]);
    }
});


//1级类目=家居日用 3 ，2级类目=收纳工具 18， 3级类目= 杂物整理 93，4级类目= 包 276 的商品，修改为：
//1级类目=家居日用 3 ，2级类目=日用小件 19，3级类目= 箱包 512，4级类目=空

$four_category_id = 276;
$targetId = 512;
$where = [
    'four_category_id ' => $four_category_id
];
$list = \Biz\model\GoodsBasicInfo::select_master('*', $where);
$secGoodsIds = array_column($list, 'goods_id');//需要修改的商品id
Category::action(function() use ($four_category_id, $targetId) {
    //修改二级分类的父id,修改类目深度
    $rs = Category::updateCataInfoById($four_category_id, ['father_id' => $targetId]);
    var_dump(['修改二级分类的父id', $rs]);
});
GoodsBasicInfo::action(function() use ($list, $targetId) {
    //商品分类修改
    foreach ($list as $value) {
        $rs = GoodsBasicInfo::update([
            'second_category_id'    => 19,
            'third_category_id'     => $targetId,
            'edittime' => date("Y-m-d H:i:s"),
        ], ['goods_id' => $value['goods_id']])->rowCount();
        var_dump(['修改商品分类,id' . $value['goods_id'], $rs]);
    }
});
$goodsIds = array_merge($goodsIds, $secGoodsIds);
sleep(10);//主从延迟
foreach ($goodsIds as $goods_id) {
    //清除商品缓存
    \Biz\cache\Goods::delItem($goods_id);
    \Biz\cache\GoodsBasicInfo::delItem($goods_id);
    //更新solr
    $info = \Biz\service\search\Goods::updateByGoodsId($goods_id);
    compact('goods_id', 'info');
}






